<?php

use think\Db;
use think\Session;
use \itbdw\Ip\IpLocation;
use think\console\output\Formatter;

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------



// 应用公共文件

//自定义添加order_good表記錄
function add_order_good($insert_id, $movegood, $enterpriseId, $type)
{
	//更新字表
	$arr = [];
	foreach ($movegood as $key => $val) {

		if (isset($val['good_id']) && isset($val['store_id']) && intval($val['good_id']) != 0 && intval($val['store_id']) != 0) {
			if (!isset($val['after_hs_price'])) {
				$val['after_hs_price'] = "";
			}
			if (!isset($val['zk_zhe'])) {
				$val['zk_zhe'] = "";
			}
			if (!isset($val['zk_price'])) {
				$val['zk_price'] = "";
			}
			if (!isset($val['xxdd_sn'])) {
		        $val['xxdd_sn'] = "";
		    }
		    if (!isset($val['xxdd_id'])) {
		        $val['xxdd_id'] = 0;
		    }
			$ins = [
				'addtime' => time(), //新增时间
				'updatetime' => time(), //更新时间
				'order_id' => $insert_id, //父id
				'enterprise_id' => $enterpriseId, //企业id
				'good_id' => intval($val['good_id']), //商品id
				'shuliang' => intval($val['shuliang']), //商品数量
				'unit_id' => intval($val['unit_id']), //单位
				'store_id' => intval($val['store_id']), //仓库id
				'use_kc' => intval($val['use_kc']), //可用库存
				'base_unit_id' => intval($val['base_unit_id']), //基本单位
				'base_number' => $val['base_number'], //基本数量
				'price' => $val['price'], //单价
				'hs_price' => $val['hs_price'], //含税单价
				'after_hs_price' => $val['after_hs_price'], //折后含税单价
				'zk_lv' => $val['zk_lv'], //折扣率
				'zk_zhe' => $val['zk_zhe'], //折扣折
				'zk_e' => $val['zk_e'], //折扣额
				'tax_lv' => $val['tax_lv'], //税率
				'zk_price' => $val['zk_price'], //折后单价
				'jine' => $val['jine'], //金额
				'tax_e' => $val['tax_e'], //税额
				'total_price' => $val['total_price'], //价税合计
				'xxdd_sn' => $val['xxdd_sn'], //以销代购销售订单sn
				'xxdd_id' => $val['xxdd_id'], //以销代购销售订单id


				'type' => $type, //订单类型
			];
			array_push($arr, $ins);
		}
	}
	if (count($arr) > 0) {
		$res = Db::name('order_good')->insertAll($arr);
		if ($res) {
			return 1;
		}
	}
	return 0;
}


/**
 * @desc 生成自定义sn
 * @param $string 编号
 * @param $type 类型（0=购货， 1=销货， 2=盘点， 3=其他出入库， 4=成本调整单， 5=组装单/拆卸单，6=其他收支单）
 */
function osn($string, $type = 1)
{
	$str = $string . date('Ymd');
	switch ($type) {
		case 1:
			$count = Db::name('order')->where('sn', 'like', $str . '%')->count();
			break;
		case 2:
			$count = Db::name('check')->where('sn', 'like', $str . '%')->count();
			break;
		case 3:
			$count = Db::name('stock_record')->where('sn', 'like', $str . '%')->count();
			break;
		case 4:
			$count = Db::name('cost_order')->where('sn', 'like', $str . '%')->count();
			break;
		case 5:
			$count = Db::name('make_order')->where('sn', 'like', $str . '%')->count();
			break;
		case 6:
			$count = Db::name('income')->where('sn', 'like', $str . '%')->count();
			break;
		default:
			# code...
			break;
	}
	$str = $str . str_pad(++$count, 4, "0", STR_PAD_LEFT);
	return $str;
}

/**
 * 递归获取结构树
 * @param  array $data  数据源
 * @param  integer $pid 父类id
 * @param  integer $level 深度
 * @return array 组装好的树
 */
function get_tree($data, $pid = 0, $level = 0, $sort = 'parentId')
{
	static $tree = array();
	foreach ($data as $key => $row) {
		if ($row['parentId'] == $pid) {
			$row['level'] = $level;
			$tree[] = $row;
			unset($data[$key]); //进入树结构后，接下里要查的就只是它的子类了，所以从$data中删除，减少后面查询次数
			get_tree($data, $row['id'], $level + 1);
		}
	}

	return $tree;
}

/**
 * 输出树结构
 * @param  array 数据源
 * @return void
 */
function getTree($tree)
{
	foreach ($tree as $row) {
		for ($i = $row['level']; $i > 0; $i--) {
			echo '|----';
		}
		echo $row['name'];
		echo '<br>';
	}
}

/**
 * @desc 根据sn获取表明
 * @param $string SN
 */
function sn_table($string)
{
	$type = strpos($string, 'XHDD'); //销售
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'XH');
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'XHT');
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'GHDD'); //购货
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'GH');
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'GHT');
	if ($type) {
		return "order";
	}
	$type = strpos($string, 'SKD'); //收付款
	if ($type) {
		return "payment";
	}
	$type = strpos($string, 'FKD');
	if ($type) {
		return "payment";
	}
}

//自定义生成查询客户总欠款=客户还欠商家多少
function user_arrears($user_id)
{
	//客户需要付款的总和
	$system_price_r = Db::name('user_money')->where('user_id', $user_id)->where('type', 0)->where('is_del', 0)->sum('system_price');
	//客户需要进款的总和
	$system_price_c = Db::name('user_money')->where('user_id', $user_id)->where('type', 1)->where('is_del', 0)->sum('system_price');

	//应收
	$system_price = $system_price_r - $system_price_c;
	//客户需要付款的总和
	$user_price_r = Db::name('user_money')->where('user_id', $user_id)->where('type', 0)->where('is_del', 0)->sum('user_price');
	//客户预收款
	//$pre_user_price_r=Db::name('user_money')->where('type',0)->sum('pre_user_price');
	//客户需要进款的总和
	$user_price_c = Db::name('user_money')->where('user_id', $user_id)->where('type', 1)->where('is_del', 0)->sum('user_price');
	//客户预收款
	//$pre_user_price_c=Db::name('user_money')->where('type',0)->sum('pre_user_price');
	//实收
	//$user_price=$user_price_r+$pre_user_price_r-$user_price_c-$pre_user_price_c;
	$user_price = $user_price_r - $user_price_c;
	$res = round($system_price - $user_price, 2); //应收-实收
	return $res;
}

//自定义生成查询客户总欠款=客户还欠商家多少
function user_meet($user_id)
{
	// 供应商收款
	$system_price = Db::name('user_money')->where('user_id', $user_id)->where('is_del', 0)->where('type', 1)->sum('system_price');
	$user_price = Db::name('user_money')->where('user_id', $user_id)->where('is_del', 0)->where('type', 1)->sum('user_price');

	return round($system_price - $user_price, 2);
}

/**
 * Polymerization search
 * @param string $field 	Main table field list
 * @param string $sonField 	Son table field list
 * @param string $keywork 	Search content
 * @param array  $value 	Son table and relation field
 * @param bool 	 $type 		Is son talbe relation main table
 * @return array $where		Search where
 */
function getSearch($field, $sonField, $keywork, $value, $type = false): array
{
	$map[$field] = ['like', '%' . $keywork . '%'];
	$sonMap[$sonField] = ['like', '%' . $keywork . '%'];
	is_array($value) ?: halt('The fourth argument to the function must be an array');
	$sonRes = Db::name($value[0])->where($sonMap)->where('is_del', 0)->select();
	$where = [];
	if ($sonRes) {
		if ($type) {
			$where['id'] = ['in', array_column($sonRes, $value[1])];
		} else {
			$where[$value[1]] = ['in', array_column($sonRes, 'id')];
		}
	} else {
		$where = $map;
	}
	return $where;
}

//新增-客户资金流水
//type  0客户付款；1客户进款
//o_way 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
function add_user_money($data)
{

	if (empty($data['pid']) && empty($data['psn'])) {
		$data['pid'] = 0;
		$data['psn'] = null;
	}
	//halt($data);
	if (!isset($data['system_price']) || !isset($data['user_price']) || !isset($data['user_id']) || !isset($data['type']) || !isset($data['o_way']) || !isset($data['pid'])) {
		//$msg='参数错误';
		return 0;
	} else {
		$data['addtime'] = time();
		$data['updatetime'] = time();
		$res = Db::name('user_money')->insert($data);
		if ($res) {
			return 1;
		}
	}
	return 0;
}

/**
 * @desc 获得多单位数据
 */
function get_multi_unit()
{
	$list = Db::name('unit')->where('pid', 0)->where('is_del', 0)->select();

	foreach ($list as $key => $value) {
		$sonUnit = Db::name('unit')->where('pid', $value['id'])->where('is_del', 0)->select();
		$list[$key]['super_name'] = $value['name'];
		foreach ($sonUnit as $k => $v) {
			$list[$key]['super_name'] .= ',' . $v['name'];
			$list[$key]['son_id'][$k] = $v['id'];
		}
		$list[$key]['super_name'] .= '(' . $value['rate'];
		foreach ($sonUnit as $k => $v) {
			$list[$key]['super_name'] .= ':' . $v['rate'];
		}
		$list[$key]['super_name'] .= ')';
	}
	return $list;
}

/**
 * @desc 根据指定的父级id获取子集单位
 */
function one_multi_unit($id)
{
	$info = Db::name('unit')->where('id', $id)->where('is_del', 0)->find();
	$sonUnit = Db::name('unit')->where('pid', $info['id'])->where('is_del', 0)->select();
	$info['super_name'] = $info['name'];
	foreach ($sonUnit as $k => $v) {
		$info['super_name'] .= ',' . $v['name'];
	}
	$info['super_name'] .= '(' . $info['rate'];
	foreach ($sonUnit as $k => $v) {
		$info['super_name'] .= ':' . $v['rate'];
	}
	$info['super_name'] .= ')';
	return $info['super_name'];
}

/**
 * @desc 获取库存
 * @param 仓库id 商品id
 * @return 返回库存数据
 */
function get_stock($store_id, $goods_id)
{
	$innum = Db::name('stock_record_good')->alias('a')->join('stock_record b', 'a.pid = b.id')->where(['b.status' => 1, 'b.is_del' => 0])->where('a.is_del', 0)->where('a.o_type', 0)->where(['store_id' => $store_id, 'good_id' => $goods_id])->sum('a.number');
	$outnum = Db::name('stock_record_good')->alias('a')->join('stock_record b', 'a.pid = b.id')->where(['b.status' => 1, 'b.is_del' => 0])->where('a.is_del', 0)->where('a.o_type', 1)->where(['store_id' => $store_id, 'good_id' => $goods_id])->sum('a.number');
	return $innum - $outnum;
}

/**
 * @desc 清除多维数组里面的空值
 * @param $arr 数组
 * @param $elemnt 指定元素
 */
function array_filter_clear($arr, $elemnt)
{
	foreach ($arr as $key => $value) {
		if (empty($value[$elemnt])) {
			unset($arr[$key]);
		}
	}
	return $arr;
}


//删除客户资金流水
function del_user_money($data, $info)
{

	$res = Db::name('user_money')->where('pid', $info['id'])->where('psn', $info['sn'])->where('user_id', $info['user_id'])->where('is_del', 0)->update($data);
	if ($res) {
		return 1;
	}
	return 0;
}

/**
 * @desc 公共删除方法
 * @param $table 表名
 * @param $id 要删除的id
 * @param $field 删除字段，默认为is_del
 */
function del($table, $id = 0, $field = 'is_del')
{
	if ($id == 0) {
		return false;
	}
	$res = Db::name($table)->where('id', $id)->update([$field => 1]);
	if ($res) {
		return true;
	} else {
		return false;
	}
}

//新增-结算账户记录
function add_account_record($data)
{
	$accountdata = $data['accountdata']; //结算账户
	$accountarr = [];
	foreach ($accountdata as $ke => $va) {
		if (isset($va['account_id'])) {
			if (isset($va['mark'])) {
				$mark = $va['mark'];
			} else {
				$mark = '';
			}
			if (isset($va['settle_sn'])) {
				$settle_sn = $va['settle_sn'];
			} else {
				$settle_sn = '';
			}
			$accountins = [
				'addtime' => time(),
				'updatetime' => time(),
				'pid' => $data['pid'],
				'psn' => $data['psn'],
				'account_id' => intval($va['account_id']), //结算账户ID
				'settle_type_id' => isset($va['settle_type_id']) ? intval($va['settle_type_id']) : null, //结算方式ID
				'account_money' => $va['jine'], //结算金额
				'settle_sn' => $settle_sn, //结算号
				'mark' => $mark, //备注
				'o_type' => $data['o_type'], //0收款单 1付款单 2销售单；3销售退货单；4购货单；5购货退货单
				'enterprise_id' => $data['enterprise_id'],
			];
			array_push($accountarr, $accountins);
		}
	}
	if (count($accountarr) > 0) {
		$res = Db::name('account_record')->insertAll($accountarr);
		if ($res) {
			return 1;
		}
	}
	return 0;
}


//自定义生成收款单，付款单的sn;1,入库2，出库
function money_sn($string)
{
	$str = $string . date('Y') . date('m') . date('d');
	$count = Db::name('payment')->where('sn', 'like', $str . '%')->count();
	$num = $count + 1;
	if ($num < 10) {
		$str = $str . '00' . $num;
	}
	if ($num >= 10 && $num < 100) {
		$str = $str . '0' . $num;
	}
	if ($num >= 100) {
		$str = $str . $num;
	}
	//'XHDD'.date('Y').date('m').date('d').rand(100,999);
	return $str;
}



//管理员日志
function adminlog($id)
{
	$adminlog = Db::name('auth_user')->find($id);
	$log['last_login_ip'] = $adminlog['last_login_ip'];
	$log['last_login_time'] = $adminlog['last_login_time'];
	$log['admin_id'] = $adminlog['id'];
	Db::name('login_log')->insert($log);
}

//自定义函数手机号隐藏中间四位
function yc_phone($str)
{
	$str = $str;
	$resstr = substr_replace($str, '****', 3, 4);
	return $resstr;
}


//二维数组转一维数组
function array_to_arr($array, $id)
{
	$arr = array();
	foreach ($array as $key => $val) {
		array_push($arr, $val[$id]);
	}
	return $arr;
}

//根据ip地址获取位置
function getlocation($ip)
{
	return IpLocation::getLocation($ip);
}

//字符串转数组
function strtoarr($data)
{
	// $find     = array("\r\n", "\r", "\n", ",,"," ","，");
	$find     = array(",,", "，");
	$replace  = array(",");
	$temp_str = str_replace($find, ',', $data);
	//dump($temp_str);exit();
	$arr   = explode(",", $temp_str);
	return $arr;
}
//判断是否包含某个字符
function checkstr($str, $key)
{ //$str字符串，$key被包含的字符
	$tmparray = explode($key, $str);
	if (count($tmparray) > 1) {
		return true;
	} else {
		return false;
	}
}
//对象转数组
function object_to_array(&$object)
{
	$object =  json_decode(json_encode($object), true);
	return  $object;
}

// 查询条件
function search($table, $data, $name = 'name')
{
	$data = depthClear($data);
	// halt($data);
	$sql = Db::name($table);
	extract($data);
	$sql = isset($data['startdate']) ? $sql->where('dj_time', '>', strtotime($startdate)) : $sql;
	$sql = isset($data['enddate']) ? $sql->where('dj_time', '<', strtotime($enddate)) : $sql;

	$data = array_diff_key($data, ['startdate' => '', 'enddate' => '']);
	array_walk($data, function ($val, $key) use ($sql) {
		$sql = $sql->where($key, $val);
	});
	$sql = isset($search) ? $sql->where($name, 'like', '%' . $search . '%') : $sql;
	return $sql;
}

// 深度清理
function depthClear($data)
{
	return array_diff_key($data, ['ajax' => '', 'page' => '', 'rows' => '', 'nd' => '', '_search' => '', 'sord' => '', 'sidx' => '']);
}

//获取短信通知模板
function get_msg_temp($id)
{
	$res = Db::name('api_message_temp')->where('id', $id)->find();
	return $res;
}
//手机短信接口
/**
 * @param type 默认yzm：验证码，shenhe：保修审核，jihuo：保修激活
 */
function send_mobile_message($telephone, $type = "yzm", $wzm = 0)
{
	//halt($wzm);
	$company['api_name'] = 'N0436166'; // 创蓝API账号
	$company['api_pass'] = 'esdSGVH63Y76c6'; // 创蓝API密码
	$company['smstitle'] = '【315云防伪】'; //短信抬头
	import("ChuanglanSmsApi.php");
	$clapi  = new ChuanglanSmsApi($company['api_name'], $company['api_pass']);

	$code = mt_rand(1000, 9999);
	//设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
	// $result = $clapi->sendSMS(trim($telephone), "【二校门】亲爱的用户您好，您的验证码为" . $code . "，此操作5分钟内有效，请尽快完成验证.本短信不用回复！");
	switch ($type) {
		case 'yzm':

			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'] . "亲爱的用户，请您刮开" . $wzm . "位置处验证码，此操作5分钟内有效，请尽快完成验证.本短信不用回复");
			break;
			/*case 'shenhe':
			$notice=Db::name('api_message_temp')->where('id',1)->value('content');
			//$result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备保修激活申请已提交，等待审核中.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone),  $company['smstitle'].$notice);
			break;*/

		default:
			break;
	}

	if (!is_null(json_decode($result))) {

		$output = json_decode($result, true);

		if (isset($output['code'])  && $output['code'] == '0') {
			// echo '发送成功';
			Session::set('sh_message', $code);
			return ['status' => 1, 'msg' => '发送成功'];
		} else {
			// echo $output['errorMsg'];
			return ['status' => 0, 'msg' => $output['errorMsg']];
		}
	} else {

		return ['status' => 0, 'msg' => $result];
	}
}

// 公共发送邮件的方法
function sendToMail($to, $title, $content)
{
	require_once './PHPMailer/PHPMailerAutoload.php';

	$mail = new \PHPMailer(); //实例化
	//使用smtp鉴权方式发送邮件
	$mail->isSMTP();
	//smtp需要鉴权 这个必须是true
	$mail->SMTPAuth = true;
	// qq 邮箱的 smtp服务器地址，这里当然也可以写其他的 smtp服务器地址
	//$mail->Host = 'smtp.qq.com';
	$mail->Host = 'smtp.qiye.163.com';
	//smtp登录的账号 这里填入字符串格式的qq号即可
	$mail->Username = config('email.name');
	// 这个就是之前得到的授权码，一共16位
	$mail->Password = config('email.code');;
	$mail->setFrom(config('email.name'));
	// $to 为收件人的邮箱地址，如果想一次性发送向多个邮箱地址，则只需要将下面这个方法多次调用即可
	if (is_array($to)) {
		foreach ($to as $key => $value) {
			$mail->addAddress($value);
		}
	} else {
		$mail->addAddress($to);
	}
	// 该邮件的主题
	$mail->Subject = $title;
	// 该邮件的正文内容
	$mail->Body = $content;

	$mail->SMTPSecure = 'ssl';
	// 设置ssl连接smtp服务器的远程服务器端口号
	$mail->Port = 465;
	// 使用 send() 方法发送邮件
	if (!$mail->send()) {
		return false;
		//return '发送失败: ' . $mail->ErrorInfo;
	} else {
		return true;
		//return "发送成功";
	}
}

// 公共发送邮件的方法
// function sendToMailwx($to, $title, $content)
// {
// 	require_once './PHPMailer/PHPMailerAutoload.php';
	
// 	$mail = new \PHPMailer(); //实例化
	   
//         $mail->IsSMTP(); // 启用SMTP
//         $mail->Host='smtp.163.com'; //smtp服务器的名称（这里以QQ邮箱为例）
//         $mail->SMTPAuth = TRUE; //启用smtp认证
//         $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
//         $mail->Password = C('MAIL_PASSWORD') ; //邮箱授权码
//         $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
//         $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
//         $mail->AddAddress($to,"尊敬的客户");
//         $mail->WordWrap = 50; //设置每行字符长度
//         $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
//         $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
//         $mail->Subject =$title; //邮件主题
//         $mail->Body = $content; //邮件内容
//         $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
//         return($mail->Send());
// 	// 使用 send() 方法发送邮件
// 	if (!$mail->send()) {
// 		return false;
// 		//return '发送失败: ' . $mail->ErrorInfo;
// 	} else {
// 		return true;
// 		//return "发送成功";
// 	}
//  }

 